package com.ang.juc.n4.t2;

import lombok.extern.slf4j.Slf4j;

import java.util.stream.IntStream;

/**
 * 3个线程，交替打印5次，分别打印a,b,c
 * 交替3次
 */
@Slf4j
public class Test1 {
    static Object obj = new Object();

    static String flag = "a";

    public static void main(String[] args) {
        IntStream.range(0,3).forEach(i->{
            Thread ta = new Thread(new PrintA(),"ta"+i);
            Thread tb = new Thread(new PrintB(),"tb"+i);
            Thread tc = new Thread(new PrintC(),"ta"+i);

            ta.start();
            tb.start();
            tc.start();
        });
    }

    //打印a
    static class PrintA implements Runnable{
        @Override
        public void run() {
            synchronized (obj){
                while (!flag.equals("a")){
                    try {
                        obj.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }

                IntStream.range(0,5).forEach((i)->{
                    log.info("a");
                });

                //打印b的线程执行
                flag = "b";
                obj.notifyAll();
            }
        }
    }
    //打印b
    static class PrintB implements Runnable{
        @Override
        public void run() {
            synchronized (obj){
                while (!flag.equals("b")){
                    try {
                        obj.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }

                IntStream.range(0,5).forEach((i)->{
                    log.info("b");
                });

                //打印c的线程执行
                flag = "c";
                obj.notifyAll();
            }
        }
    }
    //打印c
    static class PrintC implements Runnable{
        @Override
        public void run() {
            synchronized (obj){
                while (!flag.equals("c")){
                    try {
                        obj.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }

                IntStream.range(0,5).forEach((i)->{
                    log.info("c");
                });

                //打印a的线程执行
                flag = "a";
                obj.notifyAll();
            }
        }
    }
}
